package com.appkubes.fintech.restful.application.rent.service.impl;


import com.alibaba.fastjson.JSON;
import com.appkubes.fintech.common.exption.BusinessException;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.core.po.*;
import com.appkubes.fintech.core.pojo.FintechRentBillHeaderMapper;
import com.appkubes.fintech.core.pojo.FintechRentBillLinesMapper;
import com.appkubes.fintech.core.pojo.FintechRentRepayOrderMapper;
import com.appkubes.fintech.restful.application.credit.dao.CreditDao;
import com.appkubes.fintech.restful.application.credit.service.CreditService;
import com.appkubes.fintech.restful.application.pay.common.contract.response.NotifyResponse;
import com.appkubes.fintech.restful.application.pay.common.contract.response.PayModelResponse;
import com.appkubes.fintech.restful.application.pay.common.contract.response.PayQueryResponse;
import com.appkubes.fintech.restful.application.pay.wechat.request.PayRequest;
import com.appkubes.fintech.restful.application.pay.wechat.service.WeChatPayService;
import com.appkubes.fintech.restful.application.rent.dao.RentOrderDao;
import com.appkubes.fintech.restful.application.rent.enums.RentBillEnums;
import com.appkubes.fintech.restful.application.rent.enums.RentBuyEnums;
import com.appkubes.fintech.restful.application.rent.enums.RentOrderEnums;
import com.appkubes.fintech.restful.application.rent.enums.RentRePayOrderEnums;
import com.appkubes.fintech.restful.application.rent.request.RepayBeforeRequest;
import com.appkubes.fintech.restful.application.rent.request.RepayOrderRequest;
import com.appkubes.fintech.restful.application.rent.request.RepayPeriodRequest;
import com.appkubes.fintech.restful.application.rent.service.IRePayOrderService;
import com.appkubes.fintech.restful.application.rent.service.IRePayService;
import com.appkubes.fintech.restful.application.rent.service.IRentBillService;
import com.appkubes.fintech.restful.application.rent.service.IRentLinesService;
import com.appkubes.fintech.restful.application.user.dao.UserBaseInfoDao;
import com.appkubes.fintech.restful.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class RePayServiceImple implements IRePayService {

    @Autowired
    private IRentBillService rentBillService;
    @Resource
    private FintechRentBillLinesMapper linesMapper;
    @Resource
    private FintechRentBillHeaderMapper headerMapper;
    @Resource
    private IRePayOrderService rePayOrderService;
    @Resource
    private UserBaseInfoDao userBaseInfoMapper;
    @Resource
    private RentOrderDao rentOrderMapper;
    @Autowired
    private WeChatPayService weChatPayService;
    @Resource
    private FintechRentRepayOrderMapper rentRepayOrderMapper;
    @Resource
    private CreditDao creditDao;
    @Value("${pay.webchat.domain}")
    private String domain;
    @Value("${pay.webchat.backUrl}")
    private String backUrl;
    @Autowired
    private CreditService creditService;
    @Autowired
    private IRentLinesService linesService;
    /**
     * @Author: XQC 2020/1/6/22:46
     * @params: 发起支付
     * @return:
     * @Description:
     **/
    @Override
    public Response<PayModelResponse> doPay(RepayPeriodRequest request, HttpServletRequest servletRequest) {
        log.info("请求参数{}", request.toString());
        Integer period=request.getPeriod();
        Integer lowPeriod=linesService.queryBeforPeriod(request.getBillKey(),request.getPeriod());
        if(lowPeriod!=null){ // 检查是否有漏还期数
            period=lowPeriod;
        }
        request.setPeriod(period);
        FintechRentBillHeader billHeader = headerMapper.selectByPrimaryKey(request.getBillKey());
        FintechRentOrder rentOrder = rentOrderMapper.selectByPrimaryKey(billHeader.getOrderKey());
        FintechUserBaseInfo baseInfo = userBaseInfoMapper.selectByPrimaryKey(billHeader.getUserKey());
        FintechRentBillLinesExample example = new FintechRentBillLinesExample();
        FintechRentBillLinesExample.Criteria criteria = example.createCriteria();
        criteria.andBillKeyEqualTo(billHeader.getBillKey());
        criteria.andPeriodEqualTo(request.getPeriod());
        FintechRentBillLines lines = linesMapper.selectByExample(example).get(0);


        if (request.getPayAmt() != null && request.getPayAmt().multiply(new BigDecimal(100)).intValue() < (lines.getUnpayAmount() + lines.getUnpayFineAmount())) {
            return Response.fail("还款金额不足");
        }
        if (!lines.getStatus().equals(RentBillEnums.还款中.getValue()) &&
                !lines.getStatus().equals(RentBillEnums.未开始.getValue())
                && !lines.getStatus().equals(RentBillEnums.已逾期.getValue())) {
            return Response.fail("该期数已还款");
        }
//        if(!Objects.equals(lines.getStatus(),billHeader.getStatus())){
//            return Response.fail("还款期数异常，请联系客服");
//        }


//        if(!Objects.equals(lines.getPeriod(),billHeader.getUnpayPeriods())){
//            return Response.fail("请先还款第"+billHeader.getUnpayPeriods()+"期");
//        }
        Response<FintechRentRepayOrder> response = rePayOrderService.createOrder(lines, request, baseInfo, billHeader); // 保存账单
        if (request.getPayType().equals("02")) { //微信支付
            PayRequest payRequest = new PayRequest();
            payRequest.setBody(rentOrder.getGoodsTitle());
            payRequest.setSubJect(rentOrder.getGoodsTitle());
            payRequest.setNotifyUrl(domain + "rent/notify/1/02/" + response.getData().getRepayKey());
            payRequest.setIp(IpUtils.getIpAddress(servletRequest));
            payRequest.setBackUrl(backUrl+"?userKey="+baseInfo.getUserKey()+"&orderId="+response.getData().getRepayKey());
            payRequest.setPayAmt(request.getPayAmt().multiply(new BigDecimal(100)).intValue());
            payRequest.setOrderNo(response.getData().getRepayKey());
            payRequest.setPayType(request.getPayModel());
            log.info("微信请求参数{}", JSON.toJSONString(payRequest));
            Response<PayModelResponse> payResponse = weChatPayService.doPay(payRequest);
            if(payResponse.getCode()!=200){
                return Response.fail(payResponse.getMessage());
            }
            PayModelResponse  payRes=payResponse.getData();
            payRes.setOrderId(response.getData().getRepayKey());
            log.info("weChat pay参数{}", payResponse.toString());
            return Response.success(payRes);
        }
        return Response.fail("请选择正确的支付渠道");
    }

    /**
     * @Author: XQC 2020/1/6/22:46
     * @params: 发起支付
     * @return:
     * @Description:
     **/
    @Override
    public Response<PayModelResponse> doPay(RepayBeforeRequest request, HttpServletRequest servletRequest) {
        FintechRentBillHeader billHeader = headerMapper.selectByPrimaryKey(request.getBillKey());
        FintechRentOrder rentOrder = rentOrderMapper.selectByPrimaryKey(billHeader.getOrderKey());
        FintechUserBaseInfo baseInfo = userBaseInfoMapper.selectByPrimaryKey(billHeader.getUserKey());
        Integer unPay = billHeader.getSurpAmount() + billHeader.getUnpayFineAmount()+billHeader.getUnpayInterestAmount()+rentOrder.getBuyOutAmount();

        if (request.getPayAmt().multiply(new BigDecimal(100)).intValue() < unPay) {
            return Response.fail("提还金额不足");
        }

        Response<FintechRentRepayOrder> response = rePayOrderService.createOrder(request, baseInfo, billHeader); // 保存账单
        if (request.getPayType().equals("02")) { //微信支付
            PayRequest payRequest = new PayRequest();
            payRequest.setBody(rentOrder.getGoodsTitle());
            payRequest.setSubJect(rentOrder.getGoodsTitle());
            payRequest.setNotifyUrl(domain + "rent/notify/2/02/" + response.getData().getRepayKey());
            payRequest.setIp(IpUtils.getIpAddress(servletRequest));
            payRequest.setBackUrl(backUrl+"?userKey="+baseInfo.getUserKey()+"&orderId="+response.getData().getRepayKey());
            payRequest.setPayAmt(request.getPayAmt().multiply(new BigDecimal(100)).intValue());
            payRequest.setOrderNo(response.getData().getRepayKey());
            payRequest.setPayType(request.getPayModel());
            log.info("weChat request参数{}", payRequest.toString());
            Response<PayModelResponse> payResponse = weChatPayService.doPay(payRequest);
            PayModelResponse  payRes=payResponse.getData();
            payRes.setOrderId(response.getData().getRepayKey());
            log.info("weChat pay参数{}", payResponse.toString());
            return Response.success(payRes);
        }
        return Response.fail("请选择正确的支付渠道");
    }

    @Override
   public Response<PayQueryResponse> queryPay(String orderId){
        PayQueryResponse queryResponse=new PayQueryResponse();
        FintechRentRepayOrder repayOrder=rentRepayOrderMapper.selectByPrimaryKey(orderId);
        if(repayOrder.getStatus().equals(RentRePayOrderEnums.支付成功.getValue())
        ||repayOrder.getStatus().equals(RentRePayOrderEnums.还款成功.getValue())){
            queryResponse.setOrderId(orderId);
            queryResponse.setStatus(1);
            queryResponse.setUserKey(repayOrder.getUserKey());
            return Response.success(queryResponse);
        }
        if(repayOrder.getStatus().equals(RentRePayOrderEnums.支付失败.getValue())
                ||repayOrder.getStatus().equals(RentRePayOrderEnums.还款失败.getValue())){
            queryResponse.setOrderId(orderId);
            queryResponse.setStatus(2);
            queryResponse.setUserKey(repayOrder.getUserKey());
            return Response.success(queryResponse);
        }
        queryResponse.setOrderId(orderId);
        queryResponse.setStatus(0);
        queryResponse.setUserKey(repayOrder.getUserKey());
        return Response.success(queryResponse);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Throwable.class)
    public void notify(HttpServletRequest request, HttpServletResponse responseWrite, String periodType, String payType, String orderNo) {
        try {
            log.info("通知回调{},{}，{}", payType, orderNo,periodType);
            PrintWriter writer = responseWrite.getWriter();
            Response<NotifyResponse> response = Response.fail("未知支付方式");
            if ("02".equals(payType)) {  //微信支付通知
                response = weChatPayService.notify(request, responseWrite, orderNo);

            }
            log.info("通知回调Respon{}",response);
            if (response.getCode() != 200) {
                log.info("通知失败","dddddd");
                writer.println(response.getData().getResponseMeg());
                writer.close();
                return;
            }

            log.info("通知回成功",response);
            String tradeNo=response.getData().getOutTradeNo();
            log.info("通知回成功trade",tradeNo);

            FintechRentRepayOrder repayOrder = rentRepayOrderMapper.selectByPrimaryKey(orderNo);
            FintechRentOrder rentOrder = rentOrderMapper.selectByPrimaryKey(repayOrder.getRentOrderKey());
            log.info("还款还款.........");
            if ("1".equals(periodType)) {  // 分期还款
                log.info("还款还款........当前还款.");
                repayPeriod(repayOrder, rentOrder,tradeNo,false); // 分期还款
            } else if ("2".equals(periodType)) {
                log.info("还款还款........提前还款.");
                preRePay(repayOrder, rentOrder,tradeNo,true); // 分期还款
            }
           else {
                throw new BusinessException("还款方式错误");
            }
            writer.println(response.getData().getResponseMeg());
            writer.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {


        }
    }

    /**
     * @description: 还款金额
     * @author: xqc
     * @date: 2020/1/2 17:27
     * @params:
     * @return:
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Throwable.class)
    public Response repay(Integer amount, String userKey,String billkey,Boolean isBefore) {
        FintechRentBillHeader billHeader = rentBillService.selectByBillKey(billkey);
        if (Objects.isNull(billHeader)) {
            return Response.fail("账单不存在");
        }
        List<FintechRentBillLines> linesList = rentBillService.getBillLinesByBillKey(billHeader.getBillKey());
        Integer repayAmt = amount;
        Integer peroids=billHeader.getUnpayPeriods();
        for (FintechRentBillLines bill : linesList) {
            if (bill.getStatus().equals(RentBillEnums.还款中.getValue()) || bill.getStatus().equals(RentBillEnums.已逾期.getValue())) {
                repayAmt = repayBill(bill, billHeader, repayAmt,isBefore,0,peroids);
                updateLines(bill, new StringBuffer(),false,billHeader);
            }
        }
        updateHeader(billHeader, repayAmt, false); // 更新总账单
        return Response.success("还款成功");
    }




    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public Response repayFirst(String billKey){
        FintechRentBillHeader billHeader = headerMapper.selectByPrimaryKey(billKey);
        FintechRentBillLinesExample example = new FintechRentBillLinesExample();
        FintechRentBillLinesExample.Criteria criteria = example.createCriteria();
        criteria.andBillKeyEqualTo(billHeader.getBillKey());
        criteria.andPeriodEqualTo(1);
        FintechRentBillLines lines = linesMapper.selectByExample(example).get(0);

        RepayPeriodRequest periodRequest=new RepayPeriodRequest();
        periodRequest.setBillKey(billKey);
        periodRequest.setPeriod(1);
        BigDecimal totalAmt=new BigDecimal(lines.getUnpayInterestAmount()+lines.getUnpayFineAmount()+lines.getUnpayAmount());
        periodRequest.setPayAmt(totalAmt.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
        periodRequest.setPayType("3");
        FintechRentOrder rentOrder = rentOrderMapper.selectByPrimaryKey(billHeader.getOrderKey());
        FintechUserBaseInfo baseInfo = userBaseInfoMapper.selectByPrimaryKey(billHeader.getUserKey());
        Response<FintechRentRepayOrder> response = rePayOrderService.createOrder(lines, periodRequest, baseInfo, billHeader); // 保存账单
        return repayPeriod( response.getData(),  rentOrder,"123456789",false);

    }


    @Override
    public Response repayPeriod(FintechRentRepayOrder repayOrder,
                                FintechRentOrder rentOrder,String payTradeNo,Boolean isBefore) {
        FintechRentBillHeader billHeader = headerMapper.selectByPrimaryKey(repayOrder.getBillKey());
        if (Objects.isNull(billHeader)) {
            return Response.fail("账单不存在");
        }
        FintechUserBaseInfo baseInfo = userBaseInfoMapper.selectByPrimaryKey(billHeader.getUserKey());
        FintechRentBillLines line = linesMapper.selectByPrimaryKey(repayOrder.getBillLineKey());
        if (line.getStatus().equals(RentBillEnums.已提还.getValue()) || line.getStatus().equals(RentBillEnums.还款完毕.getValue()) ||
                line.getStatus().equals(RentBillEnums.逾期完成.getValue())) {
            RepayOrderRequest request1 = new RepayOrderRequest();
            request1.setRetMsg("请勿重复还款");
            request1.setRepayOrderKey(repayOrder.getRepayKey());
            request1.setPayTradeNo(payTradeNo);
            rePayOrderService.repayErr(request1);
            return Response.fail("请勿重复还款");
        }
        Integer repayAmt = repayOrder.getPayAmt();
        repayAmt = repayBill(line, billHeader, repayAmt,isBefore,0,billHeader.getUnpayPeriods());
        StringBuffer peroidsBuf = new StringBuffer();
        updateLines(line, peroidsBuf,false,billHeader);
        updateHeader(billHeader, repayAmt, false);
        payOverOrder(rentOrder, billHeader);
        RepayOrderRequest request1 = new RepayOrderRequest();
        request1.setRepayOrderKey(repayOrder.getRepayKey());
        request1.setPeriods(line.getPeriod().toString());
        request1.setPayTradeNo(payTradeNo);
        rePayOrderService.repaySuc(request1);
        return Response.success();
    }

    /**
     * @description: 提前还款
     * @author: xqc
     * @date: 2020/1/3 14:52
     * @params:
     * @return:
     */
    @Override
    public Response preRePay(FintechRentRepayOrder repayOrder, FintechRentOrder rentOrder,String payTradeNo,Boolean isBefore) {
        FintechRentBillHeader billHeader = headerMapper.selectByPrimaryKey(repayOrder.getBillKey());
        if (Objects.isNull(billHeader)) {
            throw new BusinessException("账单不存在");
        }
        FintechUserBaseInfo baseInfo = userBaseInfoMapper.selectByPrimaryKey(repayOrder.getUserKey());

        Integer unPayAmt = rentOrder.getBuyOutAmount() + billHeader.getSurpAmount() + billHeader.getUnpayFineAmount()+billHeader.getUnpayInterestAmount();
        Integer amount = repayOrder.getPayAmt(); // 金额转换
//        if (unPayAmt > amount) {
//            RepayOrderRequest request1 = new RepayOrderRequest();
//            request1.setRetMsg("还款金额不足");
//            request1.setRepayOrderKey(repayOrder.getRepayKey());
//            request1.setPayTradeNo(payTradeNo);
//            rePayOrderService.repayErr(request1);
//            throw new BusinessException("还款金额不足");
//        }
        List<FintechRentBillLines> linesList = rentBillService.getBillLinesByBillKey(billHeader.getBillKey());
        Integer repayAmt = amount;
        StringBuffer periods = new StringBuffer();
        for (FintechRentBillLines bill : linesList) { // 填坑所有账单
            if (bill.getStatus().equals(RentBillEnums.未开始.getValue()) || bill.getStatus().equals(RentBillEnums.还款中.getValue())
                    || bill.getStatus().equals(RentBillEnums.已逾期.getValue())) {
                repayAmt = repayBill(bill, billHeader, repayAmt,isBefore,0,billHeader.getUnpayPeriods());
                updateLines(bill, periods,true,billHeader);
            }
        }
        Integer changeAmt = repayAmt - rentOrder.getBuyOutAmount(); // 减去买断金额
        updateHeader(billHeader, changeAmt, true); // 更新总账单
        payOverOrder(rentOrder, billHeader);
        buyOutOrder(repayAmt, rentOrder, billHeader);
        RepayOrderRequest request1 = new RepayOrderRequest();
        request1.setRepayOrderKey(repayOrder.getRepayKey());
        request1.setPeriods(periods.toString());
        request1.setPayTradeNo(payTradeNo);
        rePayOrderService.repaySuc(request1);
        return Response.success("还款成功");
    }


    private Integer repayBill(FintechRentBillLines lines, FintechRentBillHeader header,
                              Integer amount,Boolean isBefore,Integer breaksAmt,Integer periods) {
        lines.setBreaksAmount(breaksAmt);
        if(header.getBreaksAmount()==0){
            header.setBreaksAmount(0);
        }
        header.setBreaksAmount(header.getBreaksAmount()+lines.getBreaksAmount());
        if (amount <= 0) { //金额小于零直接返回
            return amount;
        }

        if((lines.getPeriodStartDate().getTime()>new Date().getTime())&&isBefore){     //提前还款利息不还
            // 剩余利息不还
            header.setSurpFineAmount(header.getSurpFineAmount() - lines.getUnpayFineAmount()); // 剩余还款金额
            header.setRepayFineAmount(header.getRepayFineAmount()+0); //还的利息
            lines.setRepayFineAmount(0);
            lines.setUnpayFineAmount(0);
        }
        else {
            // 还罚息
            if (amount <= lines.getUnpayFineAmount()) {
                Integer payAmt = lines.getUnpayFineAmount() - amount;
                lines.setUnpayFineAmount(payAmt);
                lines.setRepayFineAmount(lines.getRepayFineAmount() + amount);
                header.setSurpFineAmount(header.getSurpFineAmount() - amount); // 剩余还款金额
                header.setRepayFineAmount(header.getRepayFineAmount() + amount);
                amount = 0;
                return amount;
            }
            int payFineAmt = lines.getUnpayFineAmount();
            lines.setUnpayFineAmount(0);
            amount = amount - payFineAmt;
            lines.setRepayFineAmount(lines.getRepayFineAmount() + payFineAmt);
            header.setSurpFineAmount(header.getSurpFineAmount() - payFineAmt);
            header.setRepayFineAmount(header.getRepayFineAmount() + payFineAmt);
        }

        if((lines.getPeriodStartDate().getTime()>new Date().getTime())&&isBefore){     //提前还款利息不还
            // 剩余利息不还
            header.setSurpInterestAmount(header.getSurpInterestAmount() - lines.getUnpayInterestAmount()); // 剩余还款金额
            header.setRepayInterest(header.getRepayInterest()+0); //还的利息
            lines.setRepayInterestAmount(0);
            lines.setUnpayInterestAmount(0);
        }
        else {
            // 还利息
            if (amount <= lines.getUnpayInterestAmount()) {
                Integer payAmt = lines.getUnpayInterestAmount() - amount;
                lines.setUnpayInterestAmount(payAmt);
                lines.setRepayInterestAmount(lines.getRepayInterestAmount() + amount);
                header.setSurpInterestAmount(header.getSurpInterestAmount() - amount); // 剩余还款金额
                header.setRepayInterest(header.getRepayInterest() + amount); //还的利息
                amount = 0;
                return amount;
            }
            int payInterestAmt = lines.getUnpayInterestAmount();
            lines.setUnpayInterestAmount(0);
            amount = amount - payInterestAmt;
            lines.setRepayInterestAmount(lines.getRepayInterestAmount() + payInterestAmt);
            header.setSurpInterestAmount(header.getSurpInterestAmount() - payInterestAmt);
            header.setRepayInterest(header.getRepayInterest() + payInterestAmt);
        }




        // 还本金
        if (amount <= lines.getUnpayAmount()) {
            Integer payAmt = lines.getUnpayAmount() - amount;
            lines.setUnpayAmount(payAmt);
            lines.setRepayAmount(lines.getRepayAmount() + amount);
            header.setRepayAmount(header.getRepayAmount() + amount);
            header.setSurpAmount(header.getSurpAmount() - amount);
            amount = 0;
            return amount;
        }
        int rePayAmt = lines.getUnpayAmount();
        lines.setUnpayAmount(0);
        lines.setRepayAmount(lines.getRepayAmount() + rePayAmt);
        header.setRepayAmount(header.getRepayAmount() + rePayAmt);
        header.setSurpAmount(header.getSurpAmount() - rePayAmt);
        amount = amount - rePayAmt;
        return amount;
    }

    private FintechRentBillLines updateLines(FintechRentBillLines lines, StringBuffer periodsBuf,Boolean isBefore,FintechRentBillHeader header) {
        if (!lines.getStatus().equals(RentBillEnums.还款中.getValue())
                && !lines.getStatus().equals(RentBillEnums.已逾期.getValue())
                && !lines.getStatus().equals(RentBillEnums.未开始.getValue())) {
            return lines;
        }
        if (lines.getUnpayAmount() > 0 || lines.getUnpayFineAmount() > 0||lines.getUnpayInterestAmount()>0) { // 还款部分
            linesMapper.updateByPrimaryKey(lines);
            periodsBuf.append(lines.getPeriod() + ",");
            return lines;
        }
        if (lines.getStatus().equals(RentBillEnums.还款中.getValue()) || lines.getStatus().equals(RentBillEnums.未开始.getValue())) {
            lines.setPayTime(new Date());
            if(isBefore){
                lines.setStatus(RentBillEnums.已提还.getValue());
            }
            else {
                lines.setStatus(RentBillEnums.还款完毕.getValue());
            }
            rentBillService.updatePayNextLines(lines,header);
        } else if (lines.getStatus().equals(RentBillEnums.已逾期.getValue())) {
            lines.setPayTime(new Date());
            lines.setStatus(RentBillEnums.逾期完成.getValue());
            rentBillService.updatePayNextLines(lines,header);
        }
        periodsBuf.append(lines.getPeriod() + ",");
        linesMapper.updateByPrimaryKey(lines);
        return lines;
    }


    private FintechRentBillHeader updateHeader(FintechRentBillHeader header, Integer changeAmt, Boolean isBefore) {
        if (header.getStatus().equals(RentBillEnums.还款完毕.getValue()) //完毕不进账
                || header.getStatus().equals(RentBillEnums.已提还.getValue()) || header.getStatus().equals(RentBillEnums.逾期完成.getValue())) {
            return header;
        }

        FintechRentBillLinesExample linesExample=new FintechRentBillLinesExample();
        FintechRentBillLinesExample.Criteria linesCri=  linesExample.createCriteria();
        linesCri.andBillKeyEqualTo(header.getBillKey());
        linesCri.andPeriodEqualTo(header.getUnpayPeriods());
        FintechRentBillLines lines=linesMapper.selectByExample(linesExample).get(0);
        header.setUnpayFineAmount(lines.getUnpayFineAmount());  // 同步还款明细
        header.setUnpayInterestAmount(lines.getUnpayInterestAmount());
        header.setUnpayAmount(lines.getUnpayAmount());

        if (header.getSurpFineAmount() <= 0 && header.getSurpAmount() <= 0&&header.getSurpInterestAmount()<=0) {
            header.setStatus(RentBillEnums.还款完毕.getValue());
            if (isBefore) { // 提前还款标记
                header.setStatus(RentBillEnums.已提还.getValue());
            }
            header.setUnpayInterestAmount(0);
            header.setUnpayFineAmount(0);
            header.setUnpayAmount(0);
        }
       else if (header.getUnpayFineAmount() <= 0 && header.getStatus().equals(RentBillEnums.已逾期.getValue())) {
            header.setStatus(RentBillEnums.还款中.getValue());
        }
       else if (header.getUnpayFineAmount() > 0) {
            header.setStatus(RentBillEnums.已逾期.getValue());
        }
        header.setUpdateTime(new Date());
        header.setRepayChangeAmount(header.getRepayChangeAmount() + changeAmt);//多余的零头处理
        headerMapper.updateByPrimaryKey(header);
        return header;
    }

    private FintechRentOrder payOverOrder(FintechRentOrder order, FintechRentBillHeader header) {

        if (header.getStatus().equals(RentBillEnums.还款完毕.getValue()) //完毕不进账
                || header.getStatus().equals(RentBillEnums.已提还.getValue()) || header.getStatus().equals(RentBillEnums.逾期完成.getValue())) {
            order.setStatus(RentOrderEnums.OVER.name());
            rentOrderMapper.updateByPrimaryKey(order);
            long time = System.currentTimeMillis() / 1000;
            rentOrderMapper.updateMallOrder(order.getOrderKey(),"completed",(int)time,(int)time);
            return order;
        }
        return order;
    }

    private FintechRentOrder buyOutOrder(Integer amt, FintechRentOrder order, FintechRentBillHeader header) {
        if (!header.getStatus().equals(RentBillEnums.还款完毕.getValue()) //判断租金是否完毕
                && !header.getStatus().equals(RentBillEnums.已提还.getValue()) && !header.getStatus().equals(RentBillEnums.逾期完成.getValue())) {
            return order;
        }
        if(order.getBuyOutRepayAmount()==null){
            order.setBuyOutRepayAmount(0);
        }
        Integer unPayAmt=order.getBuyOutAmount()-order.getBuyOutRepayAmount();
        if (unPayAmt > amt) {
            order.setBuyOutRepayAmount(order.getBuyOutRepayAmount()+amt);
            rentOrderMapper.updateByPrimaryKey(order);
            return order;
        }


        order.setBuyOutRepayAmount(order.getBuyOutRepayAmount()+amt);
        order.setBuyStatus(RentBuyEnums.已买断.getValue()); // 买断中
        rentOrderMapper.updateByPrimaryKey(order);

        creditService.recoverCredit(order.getUserKey(),order.getCreditAmount());// 恢复额度
        return order;
    }

//    @Override
//    public FintechCredit recoverCredit(FintechRentOrder order){
//        FintechCreditExample example=new FintechCreditExample();
//         example.createCriteria().andUserKeyEqualTo(order.getUserKey());
//         List<FintechCredit> creditList=creditDao.selectByExample(example);
//         if(creditList.size()<=0||order.getCreditAmount()==null){
//             return null;
//         }
//         FintechCredit credit=creditList.get(0);
//        if(credit.getFreezeAmount()==null){
//             credit.setFreezeAmount(0L);
//         }
//         credit.setFreezeAmount(credit.getFreezeAmount()-order.getCreditAmount()); // 减去使用过的
//         credit.setCreditStatus(0);
//         credit.setUpdateTime(new Date());
//         creditDao.updateByPrimaryKey(credit);
//
//         return credit;
//    }
}
